module ActionView::Helpers
  module ActiveScaffoldHelpers
	  def dry_scaffold_includes
	    active_scaffold_includes + "\n" + javascript_include_tag(ActiveScaffold::Config::Core.asset_path(:javascript, "dry_scaffold.js"))# + "\n" + stylesheet_link_tag(ActiveScaffold::Config::Core.asset_path(:stylesheet, "dry_stylesheet.css"))
    end
  end
  
  module ActiveScaffoldFormHelpers
    def active_scaffold_input(column, options)
      text_options = options.merge( :autocomplete => "off", :size => 20, :class => 'text-input' )
      case column.ui_type
        when :boolean
          check_box :record, column.name, options
        when :date
          sub_type = column.html_options[:sub_type] || :box
          action = :create if [:new, :create].include?(params[:action].to_sym)
          action = :update if [:edit, :update].include?(params[:action].to_sym)
          if defined? ActionView::Helpers::DhtmlCalendarHelper
            calendar_tag(:record, column.name, sub_type, 
                   { :class => 'date',
                     :form_name => element_form_id({:action => action}),
                     :include_blank => true, 
                     :use_month_numbers => true }.merge(text_options), calendar_options.merge(text_options))
          else
            date_select(:record, column.name, text_options)
          end
        when :datetime
          datetime_select(:record, column.name, text_options)
        when :phone
					text_field :record, column.name, text_options.merge(
                        :value => number_to_phone(@record[column.name].to_s),
                        :onblur => "PhoneDashAdd(this);return true;", 
          							:onchange => "NukeBadChars(this); return true;",
                        :size => 12)
        when :password
          password_field :record, column.name, text_options              
        when :text_area
          text_area(:record, column.name, text_options.merge(:cols => column.html_options[:cols], :rows => column.html_options[:rows]))
        when :usa_state
          priority = []
          select_options = {:include_blank => true}
          select_options.merge!(text_options)
          select_options.delete(:size)
          usa_state_select(:record, column.name, column.html_options[:priority] || priority, select_options, column.html_options)
        when :country
          priority = ["United States"]
          select_options = {:include_blank => true}
          select_options.merge!(text_options)
          country_select(:record, column.name, column.html_options[:priority] || priority, select_options, column.html_options)
        when :timezone
          time_zone_select(:record, column.name)
        else
# How do we do this?
          # if !DryScaffoldEngine.config(:upper_case_form_fields).nil? and DryScaffoldEngine.config(:upper_case_form_fields) and !column.name.include?("login") and !column.name.include?("email") and !column.name.include?("web_site")
          #   html_options[:onchange] ||= ''
          #   html_options.merge!(:onchange => html_options[:onchange] + "ToUpper(this); return true;") 
          # end
          if column.virtual?
            text_field(:record, column.name, text_options)
          elsif [:text, :string, :integer, :float, :decimal].include?(column.column.type)
            input(:record, column.name, text_options)
          else
            input(:record, column.name, options)
          end
      end
    end
    
    def calendar_options(date = nil)
      options = { 
         :firstDay => 1,
         :range => [2000, 2020],
         :step => 1,
         :showOthers => true,
         :cache => true }
      options[:date] = date unless date.nil?
      options
    end
    
  end
  
  module ActiveScaffoldListHelpers

    def render_column(record, column)
      # check for an override helper
      if column_override? column
        # we only pass the record as the argument. we previously also passed the formatted_value,
        # but mike perham pointed out that prohibited the usage of overrides to improve on the
        # performance of our default formatting. see issue #138.
        send(column_override(column), record)
      else
        value = record.send(column.name)
        if column.association.nil? or column_empty?(value)
          formatted_value = format_column(value, column)
        else
          case column.association.macro
            when :has_one, :belongs_to
              formatted_value = format_column(value.to_label)

            when :has_many, :has_and_belongs_to_many
              firsts = value.first(4).collect { |v| v.to_label }
              firsts[3] = '…' if firsts.length == 4
              formatted_value = format_column(firsts.join(', '))
          end
        end
        formatted_value
      end
    end

    def format_column(column_value, column = nil)
      if column_empty?(column_value)
        active_scaffold_config.list.empty_field_text
      else
        list_field_by_type(column, column_value)
      end
    end
    
    def list_field_by_type(column, column_value, options = {}, html_options = {})
      html = clean_column_value(column_value.to_s)
      return html if column.nil?
      column_type = column.ui_type
      case column_type 
        when :boolean
          html = check_box_tag(nil, 1, column_value || column_value == 1, :disabled => true) unless options[:raw_text_only]
          html = clean_column_value(column_value.to_s) if options[:raw_text_only]
        when :date :
          html = clean_column_value(format_date(column_value))
        when :datetime :
          html = clean_column_value(format_time(column_value))
        when :phone
          html = clean_column_value(number_to_phone(column_value.to_s))
      end
# Inline ajax is a lot of work do we really need it with the new ajax ability? - easier to change all three fields
      #FIXME 2006-12-21 Level=0 - Need to prevent column.ajax in :show action
#      html = list_field_by_type_ajax(table_row, html, column) if column.html_options and column.html_options[:ajax]
      html
    end

    def list_field_by_type_ajax(table_row, text, column)
      text = "-" if text.nil? or text.empty? # Give them something to click on
      options = {:content => {
                  :element => 'span',
                  :text => text,
                  :options => {
                    :id => "one_row_edit_" + table_row["id"].to_s + "_" + column.name}},
                 :url => {
                  :controller => params[:controller],
                  :action => 'update_one_field',
                  :field => column.name,
                  :id => table_row["id"]},
                 :ajax => {
                  :cancelText => "'Cancel'",
                  :okText => "'Update'"}}
      if column.html_options[:sub_type] == :select
          helper_method = "#{column.name}_custom_select_options".to_sym
          options[:ajax][:selectOptionsHTML] = "'" + escape_javascript(options_for_select(computed_field(table_row, helper_method), table_row[column.name]).gsub(/\n/, "")) + "'"
          options[:type] = :select
      end
      editable_content(options)
    end

    # From Coda Hale, http://blog.codahale.com/2006/01/14/a-rails-howto-simplify-in-place-editing-with-scriptaculous/
    def editable_content(options)
      options[:content] = { :element => 'span' }.merge(options[:content])
      options[:url] = {}.merge(options[:url])
      options[:ajax] = { :okText => "'Save'", :cancelText => "'Cancel'"}.merge(options[:ajax] || {})
      script = Array.new
      case options[:type] 
        when :select
          #TODO 2006-07-10 Level=0 - Per the web InPlaceSelectEditor is not good use InPlaceCollectionEditor instead!
          #http://wiki.script.aculo.us/scriptaculous/show/Ajax.In+Place+Collection+Editor
          # or
          #http://fora.pragprog.com/rails-recipes/write-your-own/post/223
          script << "new Ajax.InPlaceSelectEditor(" 
        else
          script << "new Ajax.InPlaceEditor("
      end
      script << "  '#{options[:content][:options][:id]}',"
      script << "  '#{url_for(options[:url])}',"
      script << "  {"
      script << options[:ajax].map{ |key, value| "#{key.to_s}: #{value}" }.join(", ")
      script << "  }"
      script << ")"
      content_tag(
       options[:content][:element],
       options[:content][:text],
       options[:content][:options]
      ) + javascript_tag( script.join("\n") )
    end
  end
end
